﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VSD.OneStopService.BLL;

public partial class Modules_HoSoDaKyDuyet : System.Web.UI.Page
{
    private ProfileStoreRepository pfStore = new ProfileStoreRepository();
    private List<Department> AllDepartment;

    private ProfileHistoryRepository resHistory = new ProfileHistoryRepository();// Repository Lịch sử tiếp nhận, xử lý và trả hồ sơ

    bool IsDirector = false;
    bool IsManager = false;
    bool CanViewAll = false;

    public int start = 0;
    int pageSize = 15;
    int pageSegSize = 1;
    int count = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        IsDirector = ContextUser.PermissionCollection.HasPermission(PermissionCode.LANHDAO_COQUAN);
        CanViewAll = ContextUser.PermissionCollection.HasPermission(PermissionCode.XEM_TOANBO_HOSO);
        IsManager = ContextUser.PermissionCollection.HasPermission(PermissionCode.LANHDAO_PHONG_CHUYENMON);
        pfStore = new ProfileStoreRepository();

        if (!IsPostBack)
        {
            if (IsDirector || CanViewAll)
                BindDepartment();
            else
            {
                CbDepartment.Visible = false;
                CkShowOwnerOnly.Visible = false;
            }
        }
    }

    public void Page_PreRender(object sender, EventArgs e)
    {
        BindProfiles();
    }

    private void BindProfiles()
    {
        int deptid = 0;
        string userName = string.Empty;
        string resolver = string.Empty;
        bool IncludeReturning = false;

        if (IsDirector || CanViewAll)
        {
            if (CbDepartment.SelectedIndex > 0)
            {
                deptid = int.Parse(CbDepartment.SelectedValue.ToString());
            }

            userName = (CkShowOwnerOnly.Checked ? ContextUser.UserName : string.Empty);
        }
        else if (IsManager || (ContextUser.GlobalOption.EnabledViewAll.HasValue && ContextUser.GlobalOption.EnabledViewAll.Value))
        {
            deptid = ContextUser.CurrentUser.DepartmentID.HasValue ? ContextUser.CurrentUser.DepartmentID.Value : 0;
            userName = string.Empty;
        }
        else
        {
            deptid = 0;
            resolver = ContextUser.UserName;
        }
        IncludeReturning = CbShowReturnedProf.Checked;

        List<ProfileStoreRepository.SignedProfileInfo> list =
            pfStore.GetSignedProfiles(deptid, userName, resolver, IncludeReturning, start, pageSize, out count).ToList();
        if (deptid == 0)
        {
            list.AddRange(pfStore.GetSignedProfiles(0, ContextUser.UserName, null, IncludeReturning, start, pageSize, out count).ToList());
            list = list.Distinct(new DistinctProfile()).ToList();
        }

        viewSignedProf.DataSource = list;
        viewSignedProf.DataBind();

        AspNetPager1.RecordCount = count;
        AspNetPager1.PageSize = pageSize;
        // AspNetPager1.CurrentPageIndex = 1;

        if (AspNetPager1.PageCount <= 1) divPagination.Visible = false;
    }

    private void BindDepartment()
    {
        DepartmentRepository DeptRepos = new DepartmentRepository();
        AllDepartment = DeptRepos.GetAll().OrderBy(r => r.Name).ToList();

        AllDepartment.Insert(0, new Department() { Name = "Danh sách phòng ban", ID = 0 });
        CbDepartment.DataSource = AllDepartment;
        CbDepartment.DataTextField = "Name";
        CbDepartment.DataValueField = "ID";
        CbDepartment.DataBind();
    }

    protected void viewSignedProf_ItemCommand(object source, RepeaterCommandEventArgs e)
    {

        if (IsDirector)
        {
            ProfileStore ps = pfStore.Get(int.Parse(e.CommandArgument.ToString()));

            if (!ps.IsReturned && !ps.IsWaitReturn)
            {
                ps.IsWaitReturn = true;
                ps.DepartmentReturn = DateTime.Now;
            }

            //==========Ghi log xử lý hồ sơ=================
            ProfileHistory executeHistory = new ProfileHistory()
            {
                ProfileID = ps.ID,
                StatusID = ps.Status,
                StatusName = ServiceStatusCode.CodeName(ps.Status),
                ActionName = "Hồ sơ đã chuyển ra bộ phận một cửa",
                ActionBy = ContextUser.CurrentUser.UserName,
                ProcessBy = ContextUser.CurrentUser.UserName,
                ActionDate = DateTime.Now,
                Consumer = ps.SubscriberName,
                Conclusion = ps.Conclusion
            };
            resHistory.Add(executeHistory);
            resHistory.SubmitChanges();

            pfStore.SubmitChanges();
            BindProfiles();
        }
        else
        {
            var script = "alert('Không được xử lý hồ sơ thay lãnh đạo');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "sample", script.ToString(), true);
        }
    }

    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        start = AspNetPager1.StartRecordIndex - 1;
        try
        {
            int deptid = 0;
            string userName = string.Empty;
            string resolver = string.Empty;
            bool IncludeReturning = false;

            if (IsDirector || CanViewAll)
            {
                if (CbDepartment.SelectedIndex > 0)
                {
                    deptid = int.Parse(CbDepartment.SelectedValue.ToString());
                }

                userName = (CkShowOwnerOnly.Checked ? ContextUser.UserName : string.Empty);
            }
            else if (IsManager || (ContextUser.GlobalOption.EnabledViewAll.HasValue && ContextUser.GlobalOption.EnabledViewAll.Value))
            {
                deptid = ContextUser.CurrentUser.DepartmentID.HasValue ? ContextUser.CurrentUser.DepartmentID.Value : 0;
                userName = string.Empty;
            }
            else
            {
                deptid = 0;
                resolver = ContextUser.UserName;
            }
            IncludeReturning = CbShowReturnedProf.Checked;

            List<ProfileStoreRepository.SignedProfileInfo> list =
                pfStore.GetSignedProfiles(deptid, userName, resolver, IncludeReturning, start, pageSize, out count).ToList();
            if (deptid == 0)
            {
                list.AddRange(pfStore.GetSignedProfiles(0, ContextUser.UserName, null, IncludeReturning, start, pageSize, out count).ToList());
                list = list.Distinct(new DistinctProfile()).ToList();
            }

            viewSignedProf.DataSource = list;
            viewSignedProf.DataBind();

        }
        catch (Exception)
        {

            throw;
        }
    }

    class DistinctProfile : IEqualityComparer<ProfileStoreRepository.SignedProfileInfo>
    {
        public bool Equals(ProfileStoreRepository.SignedProfileInfo x, ProfileStoreRepository.SignedProfileInfo y)
        {
            return x.ProfileCode.Equals(y.ProfileCode);
        }

        public int GetHashCode(ProfileStoreRepository.SignedProfileInfo obj)
        {
            return obj.ProfileCode.GetHashCode(); ;
        }
    }
}